# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
    scipen = 999,
    digits = 16,
    max.print = .Machine$integer.max,
    show.error.locations = TRUE,
    warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------
library(data.table)
library(ggplot2)
library(scales)
library(viridisLite)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1L)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

moved_tract_nbhd_qual_dt <-
    readRDS(
        "~/estimation-output/event_study_estimates_moved_tract_neighborhood_quality_w_vs_wout_young_kids.rds" # nolint
    )

# Map coefficients into shares (since they decompose the total moving effect)
moved_tract_nbhd_qual_dt[
    ,
    share := (estimate / sum(estimate)),
    by = .(attribute_label, parents_with_young_kids)
]

# Focus on upward moves
moved_tract_nbhd_qual_dt <- moved_tract_nbhd_qual_dt[valence == "Upward"]

# Reordering labels and cleaning up
moved_tract_nbhd_qual_dt[, header_group := as.character(NA)]
moved_tract_nbhd_qual_dt[
    attribute_label == "Opportunity Atlas",
    header_group := "OA"
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Childhood Opportunity Index",
    header_group := "COI"
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Area Deprivation Index",
    header_group := "ADI"
]
moved_tract_nbhd_qual_dt[is.na(header_group), header_group := "Quality Proxies"]

moved_tract_nbhd_qual_dt[
    attribute_label == "Opportunity Atlas",
    attribute_label := "Opportunity  \nAtlas  "
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Childhood Opportunity Index",
    attribute_label := "Childhood   \nOpportunity   \nIndex   "
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Area Deprivation Index",
    attribute_label := "Area   \nDeprivation   \nIndex   "
]

moved_tract_nbhd_qual_dt[
    attribute_label == "College+ Attainment",
    attribute_label := "College+\nAttainment"
]
moved_tract_nbhd_qual_dt[
    attribute_label == "Median Rent (2BR)",
    attribute_label := "Median Rent\n(2BR)"
]

moved_tract_nbhd_qual_dt[
    ,
    header_group :=
        factor(
            header_group,
            levels = c(
                "OA",
                "COI",
                "ADI",
                "Quality Proxies"
            )
        )
]

moved_tract_nbhd_qual_dt[
    ,
    attribute_label :=
        factor(
            attribute_label,
            levels =
                rev(
                    c(
                        "Opportunity  \nAtlas  ",
                        "Childhood   \nOpportunity   \nIndex   ",
                        "Area   \nDeprivation   \nIndex   ",
                        "Poverty",
                        "College+\nAttainment",
                        "Test Scores",
                        "Teen Birth",
                        "Single Parents",
                        "Median Rent\n(2BR)"
                    )
                )
        )
]

# Label the strata
moved_tract_nbhd_qual_dt[
    parents_with_young_kids == 1,
    bar_label := "Winners with Young Kids"
]
moved_tract_nbhd_qual_dt[
    parents_with_young_kids == 0,
    bar_label := "Winners without Young Kids"
]
moved_tract_nbhd_qual_dt[
    ,
    bar_label :=
        factor(
            bar_label,
            levels = c(
                "Winners without Young Kids",
                "Winners with Young Kids"
            )
        )
]

bar_fill <- rev(viridis(n = 2))
bar_colors <- rev(bar_fill)

figure_5_5_b <-
    ggplot(
        data = moved_tract_nbhd_qual_dt,
        aes(x = attribute_label, y = share, fill = bar_label)
    ) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw(base_size = 9.5) +
    scale_y_continuous(
        breaks = (seq.int(from = 0, to = 100, by = 10) / 100),
        expand = expansion(mult = c(0.005, 0.005))
    ) +
    labs(x = NULL, y = "Upward-Move-Share by Destination Characteristics") +
    coord_flip(ylim = c(0, 1)) +
    facet_grid(
        header_group ~ .,
        space = "free",
        scales = "free",
        switch = "y"
    ) +
    theme(
        panel.grid.minor = element_blank(), # remove actual gridlines
        panel.grid.major = element_blank(),
        legend.position = c(0.80, 0.95),
        legend.title = element_blank(),
        legend.key.size = unit(1.75, "lines"),
        strip.placement = "outside",
        panel.spacing.y = unit(0, "cm"),
        strip.text.y = element_text(angle = 270, size = 8),
        panel.border = element_blank(),
        axis.line = element_line(),
        axis.text.y = element_text(hjust = 0.5),
        legend.background = element_rect(fill = "white", color = "gray"),
        legend.text = element_text(size = 9),
        legend.key = element_rect(NA),
        legend.spacing.y = unit(2, "mm"),
        legend.key.height = unit(2, "mm"),
        legend.key.width = unit(4, "mm"),
        legend.margin = margin(t = 0, r = 0.1, b = 0.15, l = 0.1, unit = "cm")
    ) +
    scale_fill_manual(values = bar_fill) +
    guides(fill = guide_legend(, reverse = TRUE))

ggsave(
    plot = figure_5_5_b,
    filename = "~/paper/figures/figure-5.5b.png",
    width = 6,
    height = 4.5,
    dpi = 600
)

ggsave(
    plot = figure_5_5_b,
    filename = "~/paper/figures/figure-5.5b.tif",
    width = 6,
    height = 4.5,
    device = "tiff",
    dpi = 600
)

# Housekeeping
moved_tract_nbhd_qual_dt <- NULL
bar_fill <- NULL
bar_colors <- NULL
figure_5_5_b <- NULL
rm(
    moved_tract_nbhd_qual_dt,
    bar_fill,
    bar_colors,
    figure_5_5_b
)